﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BlackBox.Models
{
    public class NewsRepository
    {
        DataClassesDataContext db = new DataClassesDataContext();

        #region SingleTon patern

        private static NewsRepository instance;

        public static NewsRepository Instance
        {
            get
            {
                if (instance == null)
                    instance = new NewsRepository();
                return instance;
            }
        }

        #endregion

        #region Get All

        public IEnumerable<News> GetAllNews()
        {
            var listofNews = (from x in db.News
                              select x).OrderBy(x => x.date);

            return listofNews;
        }

        #endregion

        #region Get new News
        public IEnumerable<News> GetLatestnews()
        {
            //Select the newest two news
            var listOfNews = (from x in db.News
                              select x).Take(2).OrderBy(x => x.date);
            return listOfNews;
        }
        #endregion

        #region Get By ID

        public News GetNewsByID(int id)
        {
            News News = (from x in db.News
                         where x.id == id
                         select x).SingleOrDefault();

            return News;
        }

        #endregion

        #region Get By Name

        public News GetByName(string name)
        {
            var tempNews = (from x in db.News
                            where x.title == name
                            select x).SingleOrDefault();
            return tempNews;
        }

        #endregion

        #region Get By Date

        public IEnumerable<News> GetNewsByDate(DateTime From, DateTime To)
        {
            var listofNews = from x in db.News
                             where x.date <= From && x.date >= To
                             select x;

            return listofNews;
        }

        #endregion

        #region Add News
        public void AddNews(News newNews)
        {
            newNews.date = DateTime.Now;
            db.News.InsertOnSubmit(newNews);
            db.SubmitChanges();
        }
        #endregion

        #region Update

        public void UpdateNews(News newNews)
        {
            News oldNews = (from x in db.News
                            where x.id == newNews.id
                            select x).SingleOrDefault();


            oldNews.title = newNews.title;
            oldNews.message = newNews.message;
            oldNews.date = DateTime.Now;

            db.SubmitChanges();
        }

        #endregion
    }
}